<?php
declare (strict_types=1);

namespace app\utils;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use stdClass;

use function myException;

/**
 * jwt 加解密
 * Class JwtUtil
 * @package app\util
 */
class JwtUtil
{

    /**
     * @param array $payload
     * @return string
     */
    public static function encode(array $payload): string
    {
        // 读取配置
        $secretKey = '123123';
        $algorithm = 'HS256';
        if (!$secretKey || !$algorithm) {
            myException('缺少jwt的key或jwt的加密算法');
        }
        // 使用Firebase JWT解码并返回
        return JWT::encode($payload, $secretKey, $algorithm);
    }


    /**
     * @param string $jwt 已编码的json web token字符串
     * @return false|stdClass
     */
    public static function decode(string $jwt): bool|stdClass
    {
        // 读取配置
        $secretKey = '123123';
        $algorithm = 'HS256';
        if (!$secretKey || !$algorithm) {
            myException('缺少jwt的key或jwt的加密算法');
        }

        return JWT::decode($jwt, new Key($secretKey, $algorithm));
    }

}
